package com.sprouting.personal.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sprouting.personal.dao.MemberFamilyDao;
import com.sprouting.personal.dao.PsPasswordDao;
import com.sprouting.personal.interfaces.common.Constant;
import com.sprouting.personal.model.entity.MemberFamily;
import com.sprouting.personal.model.entity.PsPassword;
import com.sprouting.personal.model.vo.PsPasswordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 密码管理
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2022/11/11 15:20
 */
@Service
@Slf4j
public class PsPasswordService extends ServiceImpl<PsPasswordDao, PsPassword> {

    @Resource
    private PsPasswordDao psPasswordDao;
    @Resource
    private MemberFamilyDao memberFamilyDao;

    /**
     * 根据名称查询密码，主要防止重复
     * @param id 密码id，传递则忽略该ID数据
     * @param userId 用户ID
     * @param name 密码名称
     * @return
     */
    public PsPassword getPasswordByName(String id, String userId, String name) {
        return psPasswordDao.getPasswordByName(id, userId, name);
    }

    /**
     * 根据主键查询密码
     * @param id 密码主键
     * @return
     */
    public PsPassword getPasswordById(String id) {
        return psPasswordDao.getPasswordById(id);
    }

    /**
     * 根据条件查询全部的密码
     * @param psPassword 查询条件
     * @return
     */
    public List<PsPasswordVo> getPasswordAll(PsPasswordVo psPassword) {
        List<PsPasswordVo> list = psPasswordDao.getPasswordAll(psPassword);
        if (CollUtil.isEmpty(list)){
            return list;
        }
        List<String> idList = list.stream().filter(obj -> !Constant.DefaultValue.STRING.equals(obj.getUserMemberFamilyId())).map(PsPasswordVo::getUserMemberFamilyId).collect(Collectors.toList());
        if (CollUtil.isEmpty(idList)){
            return list;
        }
        List<MemberFamily> memberFamilyList = memberFamilyDao.getMemberFamilyByIdList(idList);
        Map<String, String> map = memberFamilyList.stream().collect(Collectors.toMap(MemberFamily::getId, MemberFamily::getUserName));
        for (PsPasswordVo passwordVo : list){
            String userName = map.get(passwordVo.getUserMemberFamilyId());
            if (Constant.DefaultValue.UNKNOWN_NAME.equals(userName)){
                passwordVo.setUserMemberFamilyName("-");
            } else {
                passwordVo.setUserMemberFamilyName(userName);
            }
        }
        return list;
    }
}
